package com.menghai;

import java.io.File;
import java.sql.Timestamp;

public class FileDelete {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FileDelete fd = new FileDelete();
		File file = new File("D:/233");
		fd.deleteFile(file);

	}
	public void deleteFile(File file){

		if (file.exists()) {

			if (file.isFile()) {
				String name = file.getName();
				
				if(name.endsWith(".xml")){
					File f = file.getParentFile();
					File[] filelist = f.listFiles();
					File[] xmllist = new File[filelist.length];
					int count = 0;
					for(int i =0;i<filelist.length;i++){
						String xmlName = filelist[i].getName();
						if(xmlName.endsWith(".xml") && filelist[i].length()>0){
							xmllist[count] = filelist[i];
							count ++;
						}
					}
					File saveFile = null;
					if(count>1){
						for(int i = 0;i<count-1;i++){
							
							long l = xmllist[i].lastModified();
							Timestamp ts = new Timestamp(l);
							long l1 = xmllist[i+1].lastModified();
							if(xmllist[i].length() > xmllist[i+1].length()){
								saveFile = xmllist[i];
							}else if(xmllist[i].length() < xmllist[i+1].length()){
								saveFile = xmllist[i+1];
							}else{
								if(l>l1){
									saveFile = xmllist[i];
								}else{
									saveFile = xmllist[i+1];
								}
							}
							
							System.out.println(xmllist[i].getParentFile() + "   " + xmllist[i].getName() +"  "+ts);
						}
						if(null !=saveFile){
							for(int i=0;i<filelist.length;i++){
								if(filelist[i].getName().endsWith(".xml") && !filelist[i].getName().equals(saveFile.getName())){
									filelist[i].delete();
								}
							}
						}
						
					}else if(count==0){
						deleteDirectory(f);
					}
				}
				

			} else if (file.isDirectory()) {

				File files[] = file.listFiles();
				for(int i =0;i<files.length;i++){
					if(!files[i].getName().equals("1") && !files[i].getName().equals("2") && !files[i].getName().equals("3") && !files[i].getName().equals("4")){
						deleteFile(files[i]);
					}
				}

			}
		} else {


		}
	}
	public void deleteDirectory(File file){

		   if(file.exists()){                    //閸掋倖鏌囬弬鍥︽閺勵垰鎯佺�妯烘躬

		    if(file.isFile()){                    //閸掋倖鏌囬弰顖氭儊閺勵垱鏋冩禒锟�
		     file.delete();                       //delete()閺傝纭�閺勵垰鍨归梽銈囨畱閹板繑锟�

		    }else if(file.isDirectory()){              //閸氾箑鍨俊鍌涚亯鐎瑰啯妲告稉锟介嚋閻╊喖缍�

		     File files[] = file.listFiles();               //婢圭増妲戦惄顔肩秿娑撳澧嶉張澶屾畱閺傚洣娆�files[];

		     for(int i=0;i<files.length;i++){            //闁秴宸婚惄顔肩秿娑撳澧嶉張澶屾畱閺傚洣娆�

		      this.deleteDirectory(files[i]);             //閹跺﹥鐦℃稉顏呮瀮娴狅拷閻劏绻栨稉顏呮煙濞夋洝绻樼悰宀冨嚡娴狅拷

		     }

		    }

		    file.delete();

		   }else{


		   }

		}
}
